//
//  HTAssembleKey.m
//  HTHappySale
//
//  Created by 创维海通 on 2017/9/26.
//  Copyright © 2017年 zxyywy. All rights reserved.
//

#import "HTAssembleKey.h"

@implementation HTAssembleKey

static HTAssembleKey *_instance;
+ (id)allocWithZone:(struct _NSZone *)zone{
    //调用dispatch_once保证在多线程中也只被实例化一次
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
    });
    return _instance;
}

+ (instancetype)sharedTool{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[HTAssembleKey alloc] init];
    });
    return _instance;
}

-(id)copyWithZone:(NSZone *)zone{
    return _instance;
}

- (void)assembleKey{
    if (!HTCFUDFEmptyValue(kAccessTokenKey)) {
        accessToken = HTCFUDFGetValue(kAccessTokenKey);
    }
    
    if (!HTCFUDFEmptyValue(kRefreshTokenKey)) {
        refreshToken = HTCFUDFGetValue(kRefreshTokenKey);
    }
    
    if (!HTCFUDFEmptyValue(kUserIdKey)) {
        userId = [HTCFUDFGetValue(kUserIdKey) intValue];
    }
    
    if (!HTCFUDFEmptyValue(kSignKey)) {
        signKey = HTCFUDFGetValue(kSignKey);
    }
    
    if (!HTCFUDFEmptyValue(kMobileKey)) {
        mobileStr = HTCFUDFGetValue(kMobileKey);
    }
    
    if (!HTCFUDFEmptyValue(kNickNameKey)) {
        nickname = HTCFUDFGetValue(kNickNameKey);
    }
    
    if (!HTCFUDFEmptyValue(kRoleKey)) {
        roleType = [HTCFUDFGetValue(kRoleKey) intValue];
    }
    
    
    NSString *encryptionStr = [NSString stringWithFormat:@"%@|%d|%@|%@",accessToken,userId,refreshToken,IDFV];
    NSLog(@"encryptionStr :%@",encryptionStr);
    
    NSString *privateKey = HTCFAES128EncryptUtil(encryptionStr,signKey);
    NSLog(@"privateKey:%@",privateKey);
    HTCFUDFCache(kSignServiceKey,privateKey);
    encryptionToken = privateKey;
}

- (void)clearKey{
    if(!HTCFUDFEmptyValue(kAuthorizationKey))
    {
        authorizationCode = @"";
        HTCFUDFRemove(kAuthorizationKey);
    }
    
    if (!HTCFUDFEmptyValue(kAccessTokenKey)) {
        accessToken = @"";
        HTCFUDFRemove(kAccessTokenKey);
    }
    
    if (!HTCFUDFEmptyValue(kRefreshTokenKey)) {
        refreshToken = @"";
        HTCFUDFRemove(kRefreshTokenKey);
    }
    
    if (!HTCFUDFEmptyValue(kUserIdKey)) {
        userId = -1;
        HTCFUDFRemove(kUserIdKey);
    }
    
    if (!HTCFUDFEmptyValue(kSignKey)) {
        signKey = @"";
        HTCFUDFRemove(kSignKey);
    }
    
    if (!HTCFUDFEmptyValue(kMobileKey)) {
        mobileStr = @"";
        HTCFUDFRemove(kMobileKey);
    }
    
    if (!HTCFUDFEmptyValue(kNickNameKey)) {
        nickname = @"";
        HTCFUDFRemove(kNickNameKey);
    }
    
    if (!HTCFUDFEmptyValue(kSignServiceKey)) {
        encryptionToken = @"";
        HTCFUDFRemove(kSignServiceKey);
    }
}

@end
